package com.sprint.controller;

import com.sprint.entities.CommonResult;
import com.sprint.entities.Payment;
import com.sprint.lb.LoadBalancer;
import com.sprint.lb.impl.MyLoadBalanceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.xml.ws.Service;
import java.net.URI;
import java.util.List;

@RequestMapping("/consumer")
@Slf4j
@RestController
public class OrderController {
    //public static final String payment_url  = "http://localhost:8001"; //单体方式直接写死
    public static final String payment_url  = "http://CLOUD-PAYMENT-SERVICE";  //微服务架构不能写死
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancer loadBalancer;
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody  Payment payment){

        System.out.println("create consumer开始 ： "+ payment_url+"/payment/create");
        return restTemplate.postForObject(payment_url+"/payment/create",payment,CommonResult.class );
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){

        System.out.println("get consumer开始 ： "+ payment_url+"/payment/get/"+id);
        return restTemplate.getForObject(payment_url+"/payment/get/"+id,CommonResult.class );

    }

    @GetMapping("/payment/lb")
    public String getLb(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size()<=0)
        {
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instance(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){

        String uri = "http://localhost:8001";
        String result = restTemplate.getForObject(uri+"/payment/zipkin",String.class);
        return result;
    }
}
